package com.yunchuang.utils;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * JSON 工具类
 *
 * @author ItJiange
 * @date 2023/10/26
 */
public class JSONUtils {
    private static final Logger logger= LoggerFactory.getLogger("logback");
    private static Gson gson = new Gson();
    public static String jsonObject(Object obj) {
        return gson.toJson(obj);
    }

    public static <T> T jsonToObject(String jsonMsg, Class<T> obj) {
        return gson.fromJson(jsonMsg, obj);
    }

    /**
     * 将 Object 对象转为 JSON 对象
     * 并返回前端
     * @param obj
     * @param resp
     */
    public static void writeOutJSON(Object obj, HttpServletResponse resp) {
        resp.setContentType("text/html;charset=utf-8");
        String jsonObject = jsonObject(obj);
        // 获取打印流
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("打印失败！");
        }
        writer.write(jsonObject);
        writer.flush();
        writer.close();
    }
}
